# coding=UTF-8


import os
from time import clock

def format_file(root, f):
    filename = os.path.join(root, f)
    new_file = os.path.join(root, 'format\\' + f)[:-4] + '_f.OUT'
    fop_r = open(filename, 'r')
    lines = fop_r.readlines()
    fop_w = open(new_file, 'w')
    result_list = []
    for line in lines:
        rec = line.strip().split(' ')
        result_list.append([rec, line])
    result_list = sorted(result_list, key=lambda x: x[0][0] + x[0][1])
    for rec in result_list:
        fop_w.write(rec[1])
    fop_w.close()
    fop_r.close()

def format_result(rootDir):
    list_dirs = os.walk(rootDir, topdown=False)
    files_list = []
    for root, dirs, files in list_dirs:
        print root, dirs, files
        if len(dirs) != 0:
            for f in files:
                files_list.append(f)

    for f in files_list:
        filename = os.path.join(rootDir, f)
        format_file(rootDir, f)
        print '%s is done' % filename




if __name__ == '__main__':
    t_start = clock()
    base_out_dir = 'data_check'
    format_result(base_out_dir)
    t_finish = clock()
    print('==============运行时间为：%s 秒==============' % str(t_finish - t_start))